package org.rqb.panel;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.lgooddatepicker.components.DatePicker;
import com.github.lgooddatepicker.components.TimePicker;
import com.github.lgooddatepicker.components.TimePickerSettings;
import org.rqb.Constant;
import org.rqb.config.MyConfig;
import org.rqb.frame.MyFrame;
import org.rqb.listener.ClickFrequencyKeyListener;
import org.rqb.dialog.TaskListDialog;
import org.rqb.robot.MyRobot;
import org.rqb.timer.MyTimer;
import org.rqb.ui.button.MyTextureButton;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.*;
import java.util.*;
import java.util.Timer;

import static org.rqb.Constant.DEFAULTDATETIMEFORMATTER;

public class ClickFrequencyPanel extends JPanel implements ActionListener {

    private TaskListDialog taskListDialog;

    private final MyTextureButton startBtn;
    private final MyTextureButton scheduledBtn;
    private final MyTextureButton coordinateButton;
    private final JLabel xyLabel;
    private final JTextField clickCountField;

    private final MyFrame myFrame;
    private final MyTextureButton pendingTimerBtn;
    private ClickFrequencyKeyListener clickFrequencyKeyListener;
    private final Properties config = MyConfig.getConfig();
    private final MyRobot robot = MyRobot.getInstance();

    private Timer currentTimer;
    private TimerTask currentTimerTask;


    private String defaultTimeName = "defalueName";

    // 独立的日期与时间选择器
    private DatePicker startDatePicker;
    private TimePicker startTimePicker;
    private DatePicker endDatePicker;
    private TimePicker endTimePicker;


    public ClickFrequencyPanel(JPanel cardPanel, CardLayout cardLayout, MyFrame myFrame) {
        this.myFrame = myFrame;

        setLayout(new BorderLayout(15, 15));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        /** ======= 中间信息面板 ======= **/
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new GridBagLayout());
        infoPanel.setBorder(BorderFactory.createTitledBorder("点击参数设置"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        int row = 0;

        // 鼠标坐标
        gbc.gridx = 0; gbc.gridy = row;
        infoPanel.add(new JLabel("鼠标坐标:"), gbc);

        JPanel xyPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        xyLabel = new JLabel("0 , 0");
        xyLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 15));
        xyLabel.setHorizontalAlignment(SwingConstants.CENTER);

        coordinateButton = new MyTextureButton("记录鼠标坐标");
        coordinateButton.addActionListener(this);

        // 把标签和按钮放在一行
        xyPanel.add(xyLabel);
        xyPanel.add(coordinateButton);

        gbc.gridx = 1;
        infoPanel.add(xyPanel, gbc);


        // 点击频率
        row++;
        gbc.gridx = 0; gbc.gridy = row;
        infoPanel.add(new JLabel("每秒点击次数:"), gbc);
        clickCountField = new JTextField(config.getProperty(Constant.CLICK_FREQUENCY, "0"));
        clickCountField.setHorizontalAlignment(SwingConstants.CENTER);
        gbc.gridx = 1;
        infoPanel.add(clickCountField, gbc);

        // 初始化时间输入设置（24小时制）
        TimePickerSettings timeSettings = new TimePickerSettings();
        timeSettings.use24HourClockFormat(); // 启用24小时制
        timeSettings.setAllowKeyboardEditing(true); // 允许用户手动输入
        timeSettings.setDisplayToggleTimeMenuButton(false); // 隐藏右侧时间按钮，显得更简洁

        // 开始时间（日期+时间）
        row++;
        gbc.gridx = 0; gbc.gridy = row;
        infoPanel.add(new JLabel("开始执行:"), gbc);
        JPanel startPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        startDatePicker = new DatePicker();
        startDatePicker.setDate(LocalDate.now());
        startTimePicker = new TimePicker(timeSettings);
        startTimePicker.setTime(LocalTime.now().plusMinutes(1));
        startPanel.add(startDatePicker);
        startPanel.add(startTimePicker);
        gbc.gridx = 1;
        infoPanel.add(startPanel, gbc);

        // 结束时间（日期+时间）
        row++;
        gbc.gridx = 0; gbc.gridy = row;
        infoPanel.add(new JLabel("结束执行:"), gbc);
        JPanel endPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        endDatePicker = new DatePicker();
        endDatePicker.setDate(LocalDate.now());
        endTimePicker = new TimePicker(timeSettings);
        endTimePicker.setTime(LocalTime.now().plusMinutes(2));
        endPanel.add(endDatePicker);
        endPanel.add(endTimePicker);
        gbc.gridx = 1;
        infoPanel.add(endPanel, gbc);

        add(infoPanel, BorderLayout.CENTER);

        /** ======= 底部按钮 ======= **/
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));

        startBtn = new MyTextureButton("立即执行");
        scheduledBtn = new MyTextureButton("定时执行");
        pendingTimerBtn = new MyTextureButton("待执行任务列表");

        startBtn.addActionListener(this);
        scheduledBtn.addActionListener(this);
        pendingTimerBtn.addActionListener(this);


        buttonPanel.add(startBtn);
        buttonPanel.add(scheduledBtn);
        buttonPanel.add(pendingTimerBtn);
        add(buttonPanel, BorderLayout.SOUTH);

        taskListDialog = new TaskListDialog(myFrame);
    }

    /** 更新鼠标位置 */
    public void updateMouseXy(Integer x, Integer y) {
        SwingUtilities.invokeLater(() -> xyLabel.setText(x + " , " + y));
    }

    public void openListener() {
        if (clickFrequencyKeyListener == null) {
            clickFrequencyKeyListener = new ClickFrequencyKeyListener(myFrame, this);
        }
        GlobalScreen.addNativeMouseListener(clickFrequencyKeyListener);
        coordinateButton.setEnabled(false);
        myFrame.setVisible(false);
    }

    public void closeListener() {
        GlobalScreen.removeNativeMouseListener(clickFrequencyKeyListener);
        coordinateButton.setEnabled(true);
        myFrame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == coordinateButton) {
            openListener();
        } else if (e.getSource() == startBtn) {
            startClickNow();
        } else if (e.getSource() == scheduledBtn) {
            scheduleClick();
        } else if (e.getSource() == pendingTimerBtn) {
            showTaskList();
        }
    }

    /**
     * 展示待执行任务列表
     */
    private void showTaskList() {
        if (taskListDialog == null) {
            taskListDialog = new TaskListDialog(myFrame);
        }
        taskListDialog.showDialog();
    }

    /** 立即执行点击 */
    private void startClickNow() {
        myFrame.setVisible(false);
        Coordinate coordinate = getCoordinate();
        if (coordinate == null) return;

        updateConfig(coordinate.num);

        currentTimer = new Timer();
        currentTimerTask = new TimerTask() {
            public void run() {
                robot.click(coordinate.x, coordinate.y);
            }
        };
        currentTimer.schedule(currentTimerTask, 0, 1000 / coordinate.num);
    }

    /** 定时执行 */
    private void scheduleClick() {
        LocalDateTime startDateTime = LocalDateTime.of(startDatePicker.getDate(), startTimePicker.getTime());
        LocalDateTime endDateTime = LocalDateTime.of(endDatePicker.getDate(), endTimePicker.getTime());

        if (startDateTime == null || endDateTime == null) {
            JOptionPane.showMessageDialog(myFrame, "请选择完整的开始和结束时间！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        long startMillis = Date.from(startDateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();
        long endMillis = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant()).getTime();

        if (endMillis <= startMillis) {
            JOptionPane.showMessageDialog(myFrame, "结束时间必须晚于开始时间！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        long startDelay = Math.max(0, startMillis - System.currentTimeMillis());
        long stopDelay = endMillis - System.currentTimeMillis();

        Coordinate coordinate = getCoordinate();
        if (coordinate == null) return;

        // ===== 弹出输入框让用户填写备注 =====
        String remark  = JOptionPane.showInputDialog(
                myFrame,
                "请输入任务备注（可选）：",
                "任务备注",
                JOptionPane.PLAIN_MESSAGE
        );
        defaultTimeName = "".equals(remark) ? defaultTimeName : remark;

        MyTimer startTimer = new MyTimer(defaultTimeName,LocalDateTime.now(),startDateTime,endDateTime);
        startTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                ClickFrequencyPanel.this.currentTimer = startTimer;
                ClickFrequencyPanel.this.currentTimerTask = this;
                robot.click(coordinate.x, coordinate.y);
            }
        }, startDelay, 1000 / coordinate.num);


        taskListDialog.addTask(startTimer);

        Timer stopTimer = new Timer();
        stopTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                startTimer.cancel();
                taskListDialog.removeTask(startTimer);
            }
        }, stopDelay);



        JOptionPane.showMessageDialog(myFrame,
                "已设置定时执行：\n开始时间：" + startDateTime.format(DEFAULTDATETIMEFORMATTER) + "\n结束时间：" + endDateTime.format(DEFAULTDATETIMEFORMATTER),
                "定时任务", JOptionPane.INFORMATION_MESSAGE);
    }

    private void updateConfig(int num) {
        HashMap<String, String> map = new HashMap<>();
        map.put(Constant.CLICK_FREQUENCY, String.valueOf(num));
        MyConfig.updateConfig(map);
    }

    public void stopClick() {
        if (currentTimerTask != null) currentTimerTask.cancel();
        if (currentTimer != null) currentTimer.cancel();
        taskListDialog.removeTask(currentTimer); //去除列表中的定时器
        myFrame.setVisible(true);
        JOptionPane.showMessageDialog(myFrame, "点击任务已结束", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    private Coordinate getCoordinate() {
        String[] split = xyLabel.getText().split(",");
        int x = Integer.parseInt(split[0].trim());
        int y = Integer.parseInt(split[1].trim());
        int num;
        try {
            num = Integer.parseInt(clickCountField.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(myFrame, "请输入数字", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
        if (num <= 0) {
            JOptionPane.showMessageDialog(myFrame, "每秒点击次数必须大于0", "提示", JOptionPane.INFORMATION_MESSAGE);
            return null;
        }
        return new Coordinate(x, y, num);
    }

    private static class Coordinate {
        public final int x;
        public final int y;
        public final int num;

        public Coordinate(int x, int y, int num) {
            this.x = x;
            this.y = y;
            this.num = num;
        }
    }
}
